package com.wangyadong.hobby.schedule.jobtask.teststack.test.map;

import com.wangyadong.hobby.schedule.jobtask.tree.pq.Entry;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;


/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2018/9/2612:50
 **/
public class UnSortHashMap<K, V> extends AbstractMap<K, V> {


    List<MapEntry<K, V>> table = new ArrayList();

    @Override
    public int size() {
        return table.size();
    }

    @Override
    public boolean isEmpty() {
        return size() == 0;
    }

    @Override
    public V get(K key) {
        int index = findIndex(key);
        if (-1 == index)
            return null;
        return table.get(index).getValue();
    }

    @Override
    public V put(K key, V value) {
        int index = findIndex(key);
        if (-1 == index) {
            MapEntry mapEntry = new MapEntry(key, value);
            table.add(mapEntry);
            return null;
        } else {
            MapEntry<K, V> kvMapEntry = table.get(index);
            V value1 = kvMapEntry.getValue();
            kvMapEntry.setValue(value);
            return value1;
        }

    }

    @Override
    public V remove(K key) {
        int index = findIndex(key);
        if (-1 == index) {
            return null;
        }
        MapEntry<K, V> kvMapEntry = table.get(index);
        if (index != table.size() - 1)
            table.set(index, table.get(table.size() - 1));
        table.remove(table.size() - 1);
        return kvMapEntry.getValue();
    }

    private class EntryIterator implements Iterator<Entry<K, V>> {
        private int j = 0;

        public boolean hasNext() {
            return j<table.size();
        }

        public Entry<K, V> next() {
            if (j == table.size()) {
                throw new NoSuchElementException();
            }
            return table.get(j++);
        }

    }

    private class EntryIterable implements Iterable<Entry<K, V>> {
        public Iterator iterator() {
            return new EntryIterator();
        }
    }

    @Override
    public Iterable<Entry<K, V>> entrySet() {
        return new EntryIterable();
    }

    private int findIndex(K k) {
        for (int i = 0; i < table.size(); i++) {
            K key = table.get(i).getKey();
            if (k.equals(key)) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        UnSortHashMap map = new UnSortHashMap();

        map.put("1", 1);
        map.put("2", 2);
        map.put("3", 3);
        map.put("4", 4);

        System.out.println(map.toString());
        Iterable iterable = map.entrySet();
        Iterator iterator = iterable.iterator();

        while (iterator.hasNext()){
            Entry<String, Integer> next = (  Entry<String, Integer>)iterator.next();
            System.out.println(next.getValue());
        }
    }
}
